package com.example.javagd.okHttp;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @program: oceanengine
 * @description:
 * @author: hzy
 * @create: 2021-03-12 22:20
 **/
@Component
public class MyOkHttp {

    @Autowired
    Gson gson;

    public Object GetFromServer(String url, Map<String, Object> data, Map<String, Object> header){
        Object result = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        try{
            URIBuilder ub = new URIBuilder(url);
            data.forEach((k, v) -> {
                ub.addParameter(k, v instanceof String ? (String) v : String.valueOf(v));
            });
            URL url2 = ub.build().toURL();

            Request.Builder builder = new Request.Builder()
                    .url(url2)
                    .method("GET", null);

            header.forEach((k, v) -> {
               builder.addHeader(k, v instanceof String ? (String) v : String.valueOf(v));
            });

            Request request = builder.build();
            Response response = client.newCall(request).execute();
 //           String msg = response.body().toString();
            if (response.code() == 200){
                //result =  gson.fromJson(response.body().string(), Map.class);
                result = JSONObject.parse(response.body().string());
            }
        }catch (Exception e){
            e.printStackTrace();

        }

        return result;
    }


    public Object PostToServer(String url, Map<String, Object> data, Map<String, Object> header){

        Object result = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        try{
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONObject.toJSONString(data));

            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .method("POST", body);

            header.forEach((k, v) -> {
                builder.addHeader(k, v instanceof String ? (String) v : String.valueOf(v));
            });

            Request request = builder.build();
            Response response = client.newCall(request).execute();

            if (response.code() == 200){
                //result =  gson.fromJson(response.body().string(), Map.class);
                result = JSONObject.parse(response.body().string());
            }
        }catch (Exception e){
            e.printStackTrace();

        }

        return result;
    }

}
